package com.kuangjia.scenic_spot_ticket.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuangjia.scenic_spot_ticket.entity.TicketOrder;
import com.kuangjia.scenic_spot_ticket.entity.User;
import com.kuangjia.scenic_spot_ticket.entity.ScenicSpot;
import com.kuangjia.scenic_spot_ticket.mapper.TicketOrderMapper;
import com.kuangjia.scenic_spot_ticket.mapper.UserMapper;
import com.kuangjia.scenic_spot_ticket.mapper.ScenicSpotMapper;
import com.kuangjia.scenic_spot_ticket.service.TicketOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;

@Service
public class TicketOrderServiceImpl extends ServiceImpl<TicketOrderMapper, TicketOrder> implements TicketOrderService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ScenicSpotMapper scenicSpotMapper;

    @Override
    public BigDecimal buyTicket(TicketOrder order) throws Exception {
        User user = userMapper.selectById(order.getUserId());
        ScenicSpot spot = scenicSpotMapper.selectById(order.getScenicSpotId());
        if (user == null || spot == null) throw new Exception("用户或景点不存在");
        if (order.getQuantity() == null || order.getQuantity() < 1) throw new Exception("购买数量必须为正整数");
        if (spot.getStock() == null || spot.getStock() < order.getQuantity()) throw new Exception("门票库存不足");
        BigDecimal price = spot.getPrice();
        BigDecimal total = price.multiply(BigDecimal.valueOf(order.getQuantity()));
        if (user.getBalance().compareTo(total) < 0) throw new Exception("余额不足");
        // 扣减库存
        spot.setStock(spot.getStock() - order.getQuantity());
        scenicSpotMapper.updateById(spot);
        user.setBalance(user.getBalance().subtract(total));
        userMapper.updateById(user);
        order.setTotalPrice(total);
        save(order);
        return user.getBalance();
    }
} 